package pri.zxx.excelgenerate.excelhanler;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;
import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.time.Instant;

public class PoiUtil {
    public static void excelToHtml(String fileName)
            throws Exception {
        InputStream is = new FileInputStream(fileName);

        HSSFWorkbook excelBook = new HSSFWorkbook(is);

        ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
                DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        ethc.setOutputColumnHeaders(false);
        ethc.setOutputRowNumbers(false);
        ethc.processWorkbook(excelBook);

        Document htmlDocument = ethc.getDocument();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DOMSource domSource = new DOMSource(htmlDocument);
        StreamResult streamResult = new StreamResult(out);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty(OutputKeys.METHOD, "html");
        serializer.transform(domSource, streamResult);
        out.close();

        String htmlStr = out.toString();
        htmlStr = htmlStr.replace("<html>", "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
                "<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        htmlStr = htmlStr.replace("<h2>Sheet0</h2>", "")
                .replace("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">",
                        "<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"></META>")
                .replace("<colgroup>", "")
                .replaceAll("<col width=\"98\">", "")
                .replace("</colgroup>", "")
                .replace("<style type=\"text/css\">",
                        "<style type=\"text/css\">\n" +
                                "body{font-family:SimSun}\n" +
                                "@page{ margin-top:80pt;}\n" +
                                "td{height:30px;}\n");
        File file = new File("htl.html");
        String htmlFolder = file.getParent();
        String htmlName = file.getName();
        FileUtils.writeStringToFile(new File(htmlFolder, htmlName), htmlStr, "utf-8");
        System.out.println(htmlStr);
        String pdfName = "tem\\" + Thread.currentThread().getId() + Instant.now().toEpochMilli() + ".pdf";
        convertToPdf(new FileInputStream(file), new FileOutputStream(pdfName));
    }


    /**
     * html转pdf
     *
     * @param inputStream  输入流
     * @param outputStream 输出流
     * @date : 2021/1/15 14:07
     */
    public static void convertToPdf(InputStream inputStream, OutputStream outputStream) throws IOException {

        PdfWriter pdfWriter = new PdfWriter(outputStream);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        //设置为A4大小
        pdfDocument.setDefaultPageSize(PageSize.A4);
        //添加中文字体支持
        ConverterProperties properties = new ConverterProperties();
        FontProvider fontProvider = new FontProvider();
        //        PdfFont sysFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
//        fontProvider.addFont(sysFont.getFontProgram(), "UniGB-UCS2-H");
//        ClassPathResource cpr = new ClassPathResource("files/simsun.ttc");
//
//        PdfFont ttcFont = PdfFontFactory.createTtcFont(IOUtils.toByteArray(cpr.getInputStream()), 1,
//                PdfEncodings.IDENTITY_H, false, true);
//
//        fontProvider.addFont(ttcFont.getFontProgram(), BaseFont.IDENTITY_H);
        fontProvider.addStandardPdfFonts();
        fontProvider.addSystemFonts();
        properties.setFontProvider(fontProvider);
        // 页眉
        pdfDocument.addEventHandler(PdfDocumentEvent.START_PAGE, new PageHeader("12435765434567654"));
        pdfDocument.addEventHandler(PdfDocumentEvent.END_PAGE, new PdfPageMarker(null));
        HtmlConverter.convertToPdf(inputStream, pdfDocument, properties);
        pdfWriter.close();
        pdfDocument.close();
    }

}
 
